package sb.simple.handle_interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.function.Consumer;

/**
 * 拦截器-springAOP|反射|可获取IOC容器中的bean以调用业务逻辑如service等
 *
 * 比如可以判断用户是否登录，若未登录直接中断请求处理
 */
public class RequestInterceptor implements HandlerInterceptor {
    private static final String TAG = RequestInterceptor.class.getSimpleName();

    @Override//controller调用前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(TAG + ":preHandle() in=>");
        StringBuffer requestURL = request.getRequestURL();
        System.out.println(TAG + ":请求地址requestURL:" + requestURL);

        //重定向至登录视图页
        /*if (未登录) {
            response.sendRedirect("/login/redirect");
            return false;
        }*/

        String queryString = request.getQueryString();
        System.out.println(TAG + ":请求参数queryString:" + queryString);

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(TAG + ":请求体body:" + sb.toString());

        HttpSession session = request.getSession();
        System.out.println(TAG + ":请求sessionId:" + session.getId());

        Collection<String> headerNames = response.getHeaderNames();
        System.out.println(TAG + ":响应头参数数量headerNames.size():" + headerNames.size());
        headerNames.stream().forEach(new Consumer<String>() {
            @Override
            public void accept(String header) {
                System.out.println(TAG + ":header:" + header);
            }
        });

        System.out.println(TAG + ":handler:" + handler.toString());
        //true会流到controller继续处理false直接中断处理
        return true;
    }

    @Override//controller调用后且在视图渲染前
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(TAG + ":postHandle() in");
    }

    @Override//视图渲染后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(TAG + ":afterCompletion() in");
    }
}
